package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author zsk
 * @create 2022-02-18-15:49
 */
@RestController
@Slf4j//加入日志注解
public class DishController {

    //依赖注入
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    根据菜品分类id查询菜品
    Request URL: http://localhost:8081/dish/list?categoryId=1397844263642378242&status=1
    Request Method: GET
     */
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId,Integer status,String name){

        //约定好在Redis中存在的键
        String key = "dish_" + categoryId;

        //先调用Redis查询(根据key查询值，返回list集合数据)
        List dishList = (List) redisTemplate.opsForValue().get(key);

        //如果不为空
        if (CollectionUtil.isNotEmpty(dishList)){
            //意味着在Redis中查询到了数据，直接返回
            return ResultInfo.success(dishList);
        }else {
            //证明Redis中不存在数据
            log.info("从Mysql中获取到了菜品数据");

            //从数据库中查询数据,将查询回来的数据放入到dishList集合对象中
            dishList = dishService.findByCategoryId(categoryId,name);

            //存储到Redis中
            redisTemplate.opsForValue().set(key,dishList);

            //返回结果
            return ResultInfo.success(dishList);
        }
    }
}
